package com.gexiaobao.pigeon.ui.fragment.mine.pigeon

import android.app.Dialog
import android.graphics.Bitmap
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.model.bean.FeatherColorResponse
import com.gexiaobao.pigeon.app.model.bean.PigeonBean
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.databinding.FragmentBasicInfoBinding
import com.gexiaobao.pigeon.ui.adapter.ImageAdapter
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.ui.fragment.mine.pigeon.activity.ActivityForceAnalysis
import com.gexiaobao.pigeon.viewmodel.MyPigeonViewModel
import com.youth.banner.indicator.CircleIndicator
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.startActivity

/**
 * @Author      : hxw
 * @Date        : 2023/5/31 16:48
 * @Describe    : 的赛鸽-基本信息
 */
class FragmentPigeonBasicInfo : BaseFragment<MyPigeonViewModel, FragmentBasicInfoBinding>() {

    private lateinit var colorList: ArrayList<FeatherColorResponse.ColorList>
    private var imgList: ArrayList<String> = arrayListOf()

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewmodel = mViewModel
    }

    override fun onResume() {
        super.onResume()
        showLoading(getString(R.string.loading))
        mViewModel.getFeatherColor()
    }

    override fun onStart() {
        super.onStart()
        mDatabind.banner.start()
    }

    override fun onStop() {
        super.onStop()
        mDatabind.banner.stop()
    }

    override fun initData() {
        super.initData()
        mViewModel.pigeonType.set("1")
        eventViewModel.toModifyPigeonResult.observeInFragment(this) {
            showLoading(getString(R.string.loading))
            mViewModel.getPigeonInfo(it)
        }
    }

    private fun showUIData(mPigeonData: PigeonBean.RingInfo) {
        if (mPigeonData.bodyPicPath.isEmpty() && mPigeonData.featherPicPath.isEmpty() && mPigeonData.rightHeadPicId.isEmpty() && mPigeonData.leftHeadPicPath.isEmpty()) {
            mDatabind.banner.visibility = View.GONE
        } else {
            imgList.clear()
            imgList.add(mPigeonData.bodyPicPath)
            imgList.add(mPigeonData.featherPicPath)
            imgList.add(mPigeonData.rightHeadPicId)
            imgList.add(mPigeonData.leftHeadPicPath)
        }

        mDatabind.banner.addBannerLifecycleObserver(this)//添加生命周期观察者
            .setAdapter(ImageAdapter(imgList)).setIndicator(CircleIndicator(context))
            .setLoopTime(5000).setOnBannerListener { data, _ ->
                if (data.toString().isEmpty()) {
                    RxToast.showToast(getString(R.string.the_image_resource_fail))
                    return@setOnBannerListener
                }
                bigImageLoader(data.toString())
            }
//        banner.setBannerGalleryMZ(30, 0.8f)//叠如效果
        mDatabind.banner.setBannerRound(20F)

        if (colorList.isNotEmpty()) {
            for (index in colorList.indices) {
                if (mPigeonData.featherColor == colorList[index].id) {
                    mViewModel.pigeonFeatherColor.set(colorList[index].featherColor)
                }
            }
        }

        if (mIntentType) {
            mViewModel.pigeonType.set("1")
        } else {
            mViewModel.pigeonType.set("0")
        }

        mViewModel.pigeonMasterName.set(mPigeonData.name)
        mViewModel.pigeonRingId.set(mPigeonData.ringId)
        mViewModel.pigeonRingSn.set(mPigeonData.ringSn)
        mViewModel.pigeonFather.set(mPigeonData.fatherRingId)
        mViewModel.pigeonMother.set(mPigeonData.motherRingId)
        mViewModel.pigeonRaiser.set(mPigeonData.raiser)
        mViewModel.pigeonBirthday.set(mPigeonData.birthday)
        mViewModel.pigeonDesc.set(mPigeonData.pigeonDesc)

        when (mPigeonData.sex) {
            1 -> {
                mViewModel.pigeonSex.set(getString(R.string.hint_unknown))
            }

            2 -> {
                mViewModel.pigeonSex.set(getString(R.string.hint_female))
            }

            3 -> {
                mViewModel.pigeonSex.set(getString(R.string.hint_male))
            }
        }
        when (mPigeonData.eyePattern) {
            1 -> {
                mViewModel.pigeonEyePattern.set(getString(R.string.hint_unknown))
            }

            2 -> {
                mViewModel.pigeonEyePattern.set(getString(R.string.pigeon_yellow))
            }

            3 -> {
                mViewModel.pigeonEyePattern.set(getString(R.string.pigeon_sha))
            }

            4 -> {
                mViewModel.pigeonEyePattern.set(getString(R.string.pigeon_bull))
            }
        }
    }

    private fun bigImageLoader(url: String) {
        Thread {
            val bitmap = Util.netToLoacalBitmap(url)
            val message = Message()
            message.obj = bitmap
            mHandler.sendMessage(message)
        }.start()
    }

    private var mHandler = Handler {
        if (it.obj == null) {
            RxToast.showToast(getString(R.string.the_image_resource_fail))
        } else {
            val bitmap: Bitmap = it.obj as Bitmap
            showBigImage(bitmap)
        }
        false
    }

    private fun showBigImage(bitmap: Bitmap) {
        val dialog = activity?.let { Dialog(it) }
        val image = ImageView(context)
        image.setImageBitmap(bitmap)
        dialog?.setContentView(image)
        //将dialog周围的白块设置为透明
        dialog?.window?.setBackgroundDrawableResource(android.R.color.black)
        dialog?.window?.setLayout(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        dialog?.show()
        image.setOnClickListener {
            dialog?.cancel()
        }
    }


    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.tvBasicInfoModify, mDatabind.tvBasicInfoDelete, mDatabind.tvDragging) {
            when (it) {
                mDatabind.tvDragging -> {
                    try {
                        startActivity<ActivityForceAnalysis>(
                            "pigeonId" to mPigeonId,
                            "ringId" to mPigeonData.ringId,
                            "raceId" to 0,
                            "raceType" to 0
                        )
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }

                mDatabind.tvBasicInfoModify -> {
                    nav().navigateAction(R.id.action_detail_pigeon_to_add_pigeon, Bundle().apply {
                        putString("title", getString(R.string.Pigeon_modification))
                        putSerializable("pigeonData", mPigeonData)
                        putString("featherColor", mViewModel.pigeonFeatherColor.get())
                        putInt("type", 2)
                        putInt("pigeonId", mPigeonData.pigeonId)
                    })
                }

                mDatabind.tvBasicInfoDelete -> {
                    deletePigeon()
                }
            }
        }
    }

    private fun deletePigeon() {
        val dialog = RxDialogDefault(context)
        dialog.setTitle(getString(R.string.is_delete_this_pigeon))
        dialog.setSureListener {
            showLoading(getString(R.string.loading))
            mViewModel.deletePigeon(mPigeonId)
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.deletePigeon.observe(viewLifecycleOwner) {
            dismissLoading()
            if (it.isSuccess) {
                nav().navigateUp()
                eventViewModel.toRefreshList.value = true
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        mViewModel.pigeonInfoResult.observe(viewLifecycleOwner) {
            if (it != null) {
                dismissLoading()
                mPigeonData = it
                showUIData(it)
            }
        }

        mViewModel.featherColor.observe(this) {
            if (it.isSuccess) {
                if (!it.isEmpty) colorList = it.listData!!
                mViewModel.getPigeonInfo(mPigeonId.toInt())
            } else {
                RxToast.showToast(it.errMessage)
            }
        }
    }

    companion object {
        var mPigeonId: String = ""
        var mIntentType: Boolean = false
        lateinit var mPigeonData: PigeonBean.RingInfo
        fun newInstance(
            pigeonId: String,
            pigeonData: PigeonBean.RingInfo,
            intentType: Boolean
        ): FragmentPigeonBasicInfo {
            val fragment = FragmentPigeonBasicInfo()
            mPigeonId = pigeonId
            mIntentType = intentType
            mPigeonData = pigeonData
            val bundle = Bundle()
            fragment.arguments = bundle
            return fragment
        }
    }
}